package com.load.loaders.imp;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.tmatesoft.svn.core.io.SVNRepository;

import com.database.daos.IElementDao;
import com.database.objects.*;
import com.load.batch.BatchExecutor;
import com.load.loaders.ILoader;
import com.load.utils.DiffPrintUtil;

public class LoaderMethod implements ILoader {

	private static Logger logger = Logger.getLogger("load.repository");

	private IElementDao elementDao;

	@Override
	public void loadChilds(SVNRepository svnRepository, Type type, Element<?, ?> element, BatchExecutor executor) {
		Method method = (Method) element;

		checkAddMethod(method);
		checkModifyMethod(svnRepository, method);
		checkDeleteMethod(svnRepository, method);
		elementDao.saveElement(method);
	}

	private void checkAddMethod(Method method) {
		if (method.isAddStatus()) {
			logger.info("METHOD: " + method.getLabel() + " - STATUS: added");
			method.addLinesUsingContent();
			logger.info("METHOD: " + method.getLabel() + " - " + method.getNumberChilds() + " lines");
		}
	}

	private void checkModifyMethod(SVNRepository svnRepository, Method method) {
		if (method.isModifyStatus()) {
			try {
				logger.info("METHOD: " + method.getLabel() + " - STATUS: modify");
				Method previousMethod = elementDao.getPreviousMethod(method);
				if (previousMethod != null) {
					String diff = DiffPrintUtil.doDiff(previousMethod.getContent(), method.getContent());
					method.addLinesUsingDiffContent(diff);
				} else {
					logger.warn("WARN: METHOD: " + method.getLabel() + " - doesn't previous method");
				}
				logger.info("METHOD: " + method.getLabel() + " - " + method.getNumberChilds() + " lines");
			} catch (IOException e) {
				e.printStackTrace();
				logger.error("ERROR: processing diff of " + method.getLabel());
			}
		}
	}

	private void checkDeleteMethod(SVNRepository svnRepository, Method method) {
		if (method.isDeleteStatus()) {
			logger.info("METHOD: " + method.getLabel() + " - STATUS: delete");
			Method previousMethod = elementDao.getPreviousMethod(method);
			if (previousMethod != null) {
				method.setContent(previousMethod.getContent());
				method.addLinesUsingContent();
			} else {
				logger.warn("WARN: METHOD: " + method.getLabel() + " - doesn't previous method");
			}
			logger.info("METHOD: " + method.getLabel() + " - " + method.getNumberChilds() + " lines");
		}
	}

	public void setElementDao(IElementDao elementDao) {
		this.elementDao = elementDao;
	}

}